/**
 * Created by Scoot on 2017/3/21.
 */

var isWX = false;
var payTpye = "1";
var step = getCookie("step")||"1";
var payContent = getCookie("pay-content")||"";//支付内容
var orderCode = getCookie("wait-code")||"";
var amount = getCookie("wait-amount")||0;
var isApp = false;
var equipmentType = "common";

if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    equipmentType= "ios";
} else if (/(Android)/i.test(navigator.userAgent)) {
    equipmentType = "android";
} else {
    equipmentType = "common";
}

$(function(){

    isWeiXin();

    if(step == "2"){
        weiXinPay();
    }

    /*if(payContent == "customizefinal"){
        post({
            url:"/customizeOrder/finalWechatStatus",
            data:{code:orderCode},
            success:function(data){
                if(data == "success"&&step == "2"){
                    weiXinPay();
                }
            }
        })
    }else{
        if(step == "2"){
            weiXinPay();
        }
    }*/

    //选择支付方式
    $(".pay_list").click(function(){
        payTpye = $(this).data("type");
        $(".pay_list").removeClass("pay-selected");
        $(this).addClass("pay-selected");
    });
    $(".message_alert_affirm").on("click",function(){
        $(".message_alert").addClass("tab");
    });

    $(".add_cart .btn").click(function(){

        if(equipmentType == "ios"){
            try{
                //ifApp();
                window.webkit.messageHandlers.ifApp.postMessage('');//ios换内核后用此方法调微信客户端支付
                isApp = true;
            }catch (e){
                isApp = false;
            }
        }else if(equipmentType == "android"){
            try{
                isApp = contact.ifApp();
            }catch (e){
                isApp = false;
            }
        }else{
            isApp = false;
        }

        if(step != "2"){
            if(payContent == "customimprest"){ //定制商品预付款、原装包装支付
                customImprest();
            }else{
                store(); //普通商品支付
            }
            /*if(payContent == "customimprest"){ //定制商品预付款、原装包装支付
                customImprest();
            }else if(payContent == "customizefinal"){ //定制商品尾款支付
                customizeFinalPayFor();
            }else{
                store(); //普通商品支付
            }*/
        }
    });

    $(".head-back-2").click(function(){
        go(decodeURIComponent(getCookie("productdetailgoback")));
    });

    $(".icon_cart p span").text("￥"+returnFloat(amount));
});

function customImprest(){
    if(isWX){
        if(payTpye == "1"){
            setCookie("step", "2");
            window.open(SERVER_CONTEXT_PATH+"/customizeOrder/weChatPayFor?code="+orderCode,"_self");
        }else if(payTpye == "2"){
            //go("pay_tip.html?url=customizePayFor"+"&code=" + orderCode);
            go("pay_tip.html?url="+encodeURIComponent("/alipay/customizePayFor?code=" + orderCode));
        }
    }else if(isApp==true && payTpye == "1"){
        appPay("/customizeOrder/weChatPayForAPP");
    }else if(isApp == false && payTpye == '1'){
        $(".message_alert").removeClass("tab");
    }else{  //支付宝
        go("/alipay/customizePayFor?code=" + orderCode);
    }
}

function customizeFinalPayFor(){ //定制商品尾款支付

    if(isWX){  //微信公众号微信支付
        if(payTpye == "1"){
            setCookie("step", "2");
            go("/customizeOrder/weChatPayForFinal?code="+orderCode + "&addressId=" + addressId);
        }else if(payTpye == "2"){
            go("pay_tip.html?paycontent=customize&url="+encodeURIComponent("/alipay/customizeFinalPayFor?code=" + orderCode + "&addressId=" + addressId));
        }
    }else if(isApp==true && payTpye == "1"){  //app微信支付
        appPay("/customizeOrder/weChatPayForFinalAPP");
        /*post({
            url:"/customizeOrder/weChatPayForFinalAPP",
            data:{code:orderCode},
            success:function(data){
                console.log(data)
                var p = data.split(',');
                contact.wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }
        });*/
    }else if(isApp == false && payTpye == '1'){
        $(".message_alert").removeClass("tab");
    }else{  //支付宝
        //alert("/alipay/customizeFinalPayFor?code=" + orderCode + "&addressId=" + addressId)
        go("/alipay/customizeFinalPayFor?code=" + orderCode + "&addressId=" + addressId);
    }
}

function store(){
    if(isWX){  //微信公众号微信支付
        if(payTpye == "1"){
            setCookie("step", "2");
            go("/order/weChatPayFor?orderCode="+orderCode);
        }else if(payTpye == "2"){
            var _u = encodeURIComponent(window.location.host+"/alipay/payFor?code=" + orderCode);
            go("pay_tip.html?url="+_u);
        }
    }else if(isApp==true && payTpye == "1"){  //app微信支付
        appPay("/order/weChatAppPayFor");

    }else if(isApp == false && payTpye == '1'){
        $(".message_alert").removeClass("tab");
    }else{  //支付宝
        go("/alipay/payFor?code=" + orderCode);
    }
}

function appPay(url){
    var _data = '';
    if(payContent == "customimprest"|| payContent == "customizefinal"){
        _data = {code:orderCode}
    }else{
        _data = {orderCodes:orderCode}
    }
    post({
        url:url,
        data:_data,
        success:function(data){
            var p = data.split(',');
            if(equipmentType == "ios"){
                var message = {
                    'partnerid' : p[0],
                    'prepayid' : p[1],
                    'packages' : p[2],
                    'noncestr' : p[3],
                    'timestamp' : p[4],
                    'sign' : p[5]
                };
                window.webkit.messageHandlers.wxpay.postMessage(message);
                //wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }else{
                contact.wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }
        }
    });
}

function weiXinPay(){
    var _appId = '';
    var _timeStamp= '';
    var _nonceStr = '';
    var _paySign = '';
    var _signType = '';
    var prepay_id = '';
    post({
        url:"/weChat/payForWeChatDto",
        success: function (data) {
            if(data.appId){
                _appId = data.appId;
                _timeStamp = data.timeStamp;
                _nonceStr = data.nonceStr;
                _paySign = data.paySign;
                _signType = data.signType;
                prepay_id = data.prepay_id;
                setCookie("step", "1");
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                }else{
                    onBridgeReady();
                }
            }
        }
    });
    function onBridgeReady(){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId":_appId,     //公众号名称，由商户传入
                "timeStamp":_timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr":_nonceStr, //随机串
                "package":prepay_id,
                "signType":_signType,         //微信签名方式：
                "paySign":_paySign //微信签名
            },
            function(res){

                if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    go("/payresult/success.html");
                    /*if(payContent == "customimprest"||payContent == "customizefinal"){
                        go("/customize/orderlist/index.html");
                    }else{
                        go("/member/myorders/allorder.html");
                    }*/
                }else{
                    go("/payresult/fail.html");
                    /*if(payContent == "customimprest"||payContent == "customizefinal"){
                        go("/customize/orderlist/waitpay.html");
                    }else{
                        go("/member/myorders/obligation.html");
                    }*/
                }
            }
        );
    }
}

function iosApp(str){
    isApp = true;
    return true;
}

//判断是否是微信
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        isWX = true;
        return true;
    }else{
        isWX = false;
        return false;
    }
}